package com.woyou.fragment;

import java.util.ArrayList;
import java.util.List;

import retrofit.RetrofitError;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jing.biandang.R;
import com.woyou.activity.HomeActivity;
import com.woyou.adapter.SoldoutAdapter;
import com.woyou.adapter.SoldoutLeftAdapter;
import com.woyou.adapter.SoldoutRightAdapter;
import com.woyou.adapter.SuperViewPagerAdapter;
import com.woyou.bean.GoodsState;
import com.woyou.bean.GoodsTypeInfo;
import com.woyou.bean.rpc.QueryGoodsStateListReq;
import com.woyou.bean.rpc.QueryTypeListReq;
import com.woyou.bean.rpc.Result;
import com.woyou.bean.rpc.UpdateGoodsStateReq;
import com.woyou.component.SuperUI;
import com.woyou.event.EventRefreshAllView;
import com.woyou.listener.ItemClickListener;
import com.woyou.listener.SoldoutPageChangeListener;
import com.woyou.model.GoodsManagerModel;
import com.woyou.model.rpc.GoodsModel;
import com.woyou.utils.LoginUtils;
import com.woyou.utils.ThreadPoolManager;

import de.greenrobot.event.EventBus;

public class SoldoutFragment extends SuperFragment implements OnClickListener {
	private HomeActivity homeActivity;
	private View layout_soldout;
	private RelativeLayout layout_soldout_all_bar;
	private RelativeLayout layout_soldout_some_bar;
	private int screenWidth;
	private ImageView layout_soldout_navi_iv;
	private ViewPager layout_soldout_vp;
	private View layout_soldout_all;
	private View layout_soldout_some;
	private SuperViewPagerAdapter superViewPagerAdapter;
	// 所有商品
	// 左边
	private ListView layout_soldout_allleft_lv;
	private SoldoutLeftAdapter allLeftAdapter;
	public List<GoodsTypeInfo> allLeftData = new ArrayList<GoodsTypeInfo>();
	private int currentCheck = 0;
	// 右边
	private List<GoodsState> allGroupData = new ArrayList<GoodsState>();
	private ListView layout_soldout_allright_lv;
	private SoldoutRightAdapter soldoutRightAdapter;

	// 暂缺商品
	public TextView layout_soldout_num;
	private View item_soldout_header;
	private TextView item_soldout_header_info;
	private ImageView item_soldout_header_arrow;
	private ListView layout_soldout_some_lv;
	private SoldoutAdapter soldoutAdapter;
	public List<GoodsState> soldoutData = new ArrayList<GoodsState>();

	// 提交面板
	public LinearLayout layout_soldout_panel;
	private RelativeLayout layout_soldout_submit;
	private RelativeLayout layout_soldout_cancel;
	//重试
	private RelativeLayout layout_soldout_tryagain;
	private RelativeLayout layout_soldout_tryagain_b;
	//
	private GoodsModel goodsModel;
	private GoodsManagerModel goodsManagerModel=GoodsManagerModel.getInstance();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		layout_soldout = inflater.inflate(R.layout.layout_soldout, container,false);
		homeActivity=(HomeActivity)getActivity();
		goodsModel = GoodsModel.getInstance(homeActivity);
		return layout_soldout;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		// 计算位置
		DisplayMetrics dm = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
		screenWidth = dm.widthPixels;
		layout_soldout_navi_iv = (ImageView) layout_soldout.findViewById(R.id.layout_soldout_navi_iv);
		LayoutParams layoutParams = layout_soldout_navi_iv.getLayoutParams();
		layoutParams.width = screenWidth / 2;
		layout_soldout_navi_iv.setLayoutParams(layoutParams);

		// 导航栏菜单
		layout_soldout_some_bar = (RelativeLayout) layout_soldout.findViewById(R.id.layout_soldout_some_bar);
		layout_soldout_all_bar = (RelativeLayout) layout_soldout.findViewById(R.id.layout_soldout_all_bar);
		layout_soldout_num = (TextView) layout_soldout.findViewById(R.id.layout_soldout_num);
		//重试
		layout_soldout_tryagain=(RelativeLayout)layout_soldout.findViewById(R.id.layout_soldout_tryagain);
		layout_soldout_tryagain_b=(RelativeLayout)layout_soldout.findViewById(R.id.layout_soldout_tryagain_b);
		layout_soldout_tryagain_b.setOnClickListener(this);

		// 初始化Viewpager
		layout_soldout_vp = (ViewPager) layout_soldout.findViewById(R.id.layout_soldout_vp);
		List<View> views = new ArrayList<View>();
		layout_soldout_some = View.inflate(homeActivity,R.layout.layout_soldout_some, null);
		layout_soldout_all = View.inflate(homeActivity,R.layout.layout_soldout_all, null);
		views.add(layout_soldout_some);
		views.add(layout_soldout_all);
		superViewPagerAdapter = new SuperViewPagerAdapter(views);
		layout_soldout_vp.setAdapter(superViewPagerAdapter);
		layout_soldout_vp.setOnPageChangeListener(new SoldoutPageChangeListener(this,screenWidth, layout_soldout_navi_iv));
		//
		layout_soldout_panel = (LinearLayout) layout_soldout.findViewById(R.id.layout_soldout_panel);
		layout_soldout_submit = (RelativeLayout) layout_soldout.findViewById(R.id.layout_soldout_submit);
		layout_soldout_cancel = (RelativeLayout) layout_soldout.findViewById(R.id.layout_soldout_cancel);
		layout_soldout_submit.setOnClickListener(this);
		layout_soldout_cancel.setOnClickListener(this);
		// 暂缺商品
		layout_soldout_some_lv = (ListView) layout_soldout_some
				.findViewById(R.id.layout_soldout_some_lv);
		soldoutAdapter = new SoldoutAdapter(homeActivity, SoldoutFragment.this,
				soldoutData);
		item_soldout_header = View.inflate(homeActivity,R.layout.item_soldout_header, null);
		item_soldout_header_info = (TextView) item_soldout_header
				.findViewById(R.id.item_soldout_header_info);
		item_soldout_header_arrow = (ImageView) item_soldout_header
				.findViewById(R.id.item_soldout_header_arrow);
		layout_soldout_some_lv.addHeaderView(item_soldout_header);
		layout_soldout_some_lv.setAdapter(soldoutAdapter);
		// 全部商品数据
		// 左边
		layout_soldout_allleft_lv = (ListView) layout_soldout_all.findViewById(R.id.layout_soldout_allleft_lv);
		allLeftAdapter = new SoldoutLeftAdapter(getActivity(), allLeftData);
		layout_soldout_allleft_lv.setAdapter(allLeftAdapter);
		// 点击左边item
		layout_soldout_allleft_lv.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
						allLeftAdapter.setSelectItem(position);
						allLeftAdapter.notifyDataSetInvalidated();
						currentCheck = position;
						// 刷新右边数据
						loadGoodsByType(allLeftData.get(currentCheck).gettId());
					}
				});
		// 右边
		layout_soldout_allright_lv = (ListView) layout_soldout_all
				.findViewById(R.id.layout_soldout_allright_lv);
		soldoutRightAdapter = new SoldoutRightAdapter(homeActivity,
				SoldoutFragment.this, allGroupData);
		layout_soldout_allright_lv.setAdapter(soldoutRightAdapter);

		// 设置导航监听器
		layout_soldout_some_bar.setOnClickListener(new ItemClickListener(0,layout_soldout_vp));
		layout_soldout_all_bar.setOnClickListener(new ItemClickListener(1,layout_soldout_vp));

		// 加载数据
		loadSoldoutData();
		loadTypeData();
	}

	/**
	 * 加载暂缺商品列表
	 */
	public void loadSoldoutData() {
		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					QueryGoodsStateListReq queryGoodsStateListReq = new QueryGoodsStateListReq();
					queryGoodsStateListReq.setsId(LoginUtils.getUserInfo(homeActivity).getsId());
					queryGoodsStateListReq.setPwd(LoginUtils.getUserInfo(homeActivity).getPwd());
					queryGoodsStateListReq.settId("-1");
					Result<List<GoodsState>> result = goodsModel.queryGoodsStateList(queryGoodsStateListReq);
					if (result != null && result.code == 1&&result.getData()!=null&&result.getData().size()>0) {
						goodsManagerModel.addGoodsList2DataSource(result.getData());
						refreshSoldoutView(result.getData());
						isShowPanel();
						handleSoldoutGoods();
					}else if(result!=null&&result.getCode()==-3){
						homeActivity.homeController.exitLogin();
					}
				} catch (RetrofitError error) {
					switch(error.getKind()){
					case CONVERSION:
					case HTTP:
					case NETWORK:
					case UNEXPECTED:
						showTryagainView();
						break;
					}
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}

	/**
	 * 加载商品类别列表
	 */
	public void loadTypeData() {
		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					QueryTypeListReq queryTypeListReq = new QueryTypeListReq();
					queryTypeListReq.setsId(LoginUtils.getUserInfo(homeActivity).getsId());
					queryTypeListReq.setPwd(LoginUtils.getUserInfo(homeActivity).getPwd());
					Result<List<GoodsTypeInfo>> result = goodsModel.queryTypeList(queryTypeListReq);
					if (result != null && result.getCode() == 1&&result.getData() != null&& result.getData().size() > 0) {
						refreshTypeView(result.getData());
						loadGoodsByType(result.getData().get(0).gettId());
					}else if(result!=null&&result.getCode()==-3){
						homeActivity.homeController.exitLogin();
					}
				} catch (RetrofitError error) {
					switch(error.getKind()){
					case CONVERSION:
					case HTTP:
					case NETWORK:
					case UNEXPECTED:
						showTryagainView();
						break;
					}
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}

	/**
	 * 根据商品类别加载商品列表
	 */
	public void loadGoodsByType(final String tid) {

		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					QueryGoodsStateListReq goodsStateListReq = new QueryGoodsStateListReq();
					goodsStateListReq.setsId(LoginUtils.getUserInfo(homeActivity).getsId());
					goodsStateListReq.setPwd(LoginUtils.getUserInfo(homeActivity).getPwd());
					goodsStateListReq.settId(tid);
					Result<List<GoodsState>> result = goodsModel.queryGoodsStateList(goodsStateListReq);
					if (result != null && result.getCode() == 1&&result.getData()!=null) {
						goodsManagerModel.addGoodsList2DataSource(result.getData());
						refreshAllView(goodsManagerModel.getGoodsListByTid(tid));
					}else if(result!=null&&result.getCode()==-3){
						homeActivity.homeController.exitLogin();
					}
				} catch (RetrofitError error) {
					switch(error.getKind()){
					case CONVERSION:
					case HTTP:
					case NETWORK:
					case UNEXPECTED:
						showTryagainView();
						break;
					}
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}
	/**
	 * 设置商品状态
	 */
	public void setGoodsState(){
		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					UpdateGoodsStateReq updateGoodsStateReq = new UpdateGoodsStateReq();
					updateGoodsStateReq.setsId(LoginUtils.getUserInfo(homeActivity).getsId());
					updateGoodsStateReq.setPwd(LoginUtils.getUserInfo(homeActivity).getPwd());
					updateGoodsStateReq.setGoodsList(goodsManagerModel.getGoodsItemInfoData());

					final Result result = goodsModel.updateGoodsState(updateGoodsStateReq);
					if (result != null && result.getCode() == 1) {
						goodsManagerModel.submitChangeData();
						isShowPanel();
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								SuperUI.openToast(homeActivity, ""+result.getMsg());
							}
						});
					}else if(result!=null&&result.getCode()==-3){
						homeActivity.homeController.exitLogin();
					}
				} catch (RetrofitError error) {
					homeActivity.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							SuperUI.openToast(homeActivity, "提交失败！请重试");
						}
					});
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}

	/**
	 * 刷新暂缺列表
	 */
	public void refreshSoldoutView(final List<GoodsState> data) {
		homeActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				soldoutData.clear();
				soldoutData.addAll(data);
				soldoutAdapter.notifyDataSetChanged();
			}
		});
	}

	/**
	 * 刷新类别列表
	 */
	public void refreshTypeView(final List<GoodsTypeInfo> data) {
		homeActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				allLeftData.clear();
				allLeftData.addAll(data);
				allLeftAdapter.notifyDataSetChanged();
			}
		});
	}

	/**
	 * 刷新所有商品列表
	 */
	public void refreshAllView(final List<GoodsState> data) {
		homeActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				allGroupData.clear();
				allGroupData.addAll(data);
				soldoutRightAdapter.notifyDataSetChanged();
			}
		});

	}

	/**
	 * 刷新所有商品列表
	 */
	public void onEvent(EventRefreshAllView event){
		soldoutRightAdapter.notifyDataSetChanged();
		refreshSoldoutView(goodsManagerModel.getSoldoutData());
		isShowPanel();
		handleSoldoutGoods();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_soldout_submit:
			setGoodsState();
			break;
		case R.id.layout_soldout_cancel:
			goodsManagerModel.resetChangeData();
			refreshSoldoutView(goodsManagerModel.getSoldoutData());
			handleSoldoutGoods();
			isShowPanel();
			break;
		case R.id.layout_soldout_tryagain_b:
			// 加载数据
			layout_soldout_tryagain.setVisibility(View.GONE);
			loadSoldoutData();
			loadTypeData();
			break;
		default:
			break;
		}
	}
	
	
	
	/**
	 * 判断是否显示操作面板
	 */
	public void isShowPanel(){
		homeActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				//判断是否显示提交按钮
				if(	goodsManagerModel.getChangeData().size()>0){
					layout_soldout_panel.setVisibility(View.VISIBLE);
				}else{
					layout_soldout_panel.setVisibility(View.GONE);
				}
			}
		});		
	}

	/**
	 * 处理暂缺商品
	 */
	public void handleSoldoutGoods(){
		homeActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				List<GoodsState> soldoutData =goodsManagerModel.getSoldoutData();
				if (soldoutData.size()>0) {
					if (soldoutData.size() >= 1) {
						layout_soldout_num.setText("暂缺商品（"+ soldoutData.size() + "）");
						item_soldout_header_info.setText(Html.fromHtml("当前共有<big><big>"+ soldoutData.size()+ "</big></big>商品暂缺，点击按钮即可恢复"));
						item_soldout_header_arrow.setImageResource(R.raw.soldout_arrow_down);
					} else {
						item_soldout_header_info.setText("还没暂缺商品，点击设置");
						item_soldout_header_arrow.setImageResource(R.raw.soldout_arrow_up);
						layout_soldout_num.setText("暂缺商品");
					}
				} else {
					item_soldout_header_info.setText("还没暂缺商品，点击设置");
					item_soldout_header_arrow.setImageResource(R.raw.soldout_arrow_up);
					layout_soldout_num.setText("暂缺商品");
				}
			}
		});

	}

	/**
	 * 显示重试页面
	 */
	private void showTryagainView(){
		homeActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				layout_soldout_tryagain.setVisibility(View.VISIBLE);
			}
		});
	}
	@Override
	public void onPause() {
		super.onPause();
		EventBus.getDefault().unregister(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		EventBus.getDefault().register(this);
	}

}